from datetime import datetime
from typing import List

from sqlalchemy import and_, select, update
from sqlalchemy.ext.asyncio import AsyncSession

from app.bot.services.date_time import get_date_time
from app.database.models import Order, User
from app.database.services.users import get_user


async def update_order_expiring(
    session: AsyncSession,
    order_id: int,
    extended_expiring_on: datetime,
    summ: float,
    user_id: int,
) -> None:

    cur_date = get_date_time()
    user = await get_user(session, user_id)

    if user.balance < summ:
        raise ValueError("User balance is less than renewal summ")

    user.balance = user.balance - summ

    q = (
        update(Order)
        .where(Order.id == order_id)
        .values(
            expiring_on=extended_expiring_on,
            was_renewed=cur_date,
            summ_total=Order.summ_total + summ,
        )
    )

    await session.execute(q)

    await session.commit()
